package com.application.followdroid;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class Search extends Activity {
	
	private ProgressDialog search;
	private ProgressDialog follow_user;
	private ArrayList<String> query_myuser;
	private String follower;
	
	private Intent login_user;
	private String pkg_search;
	private String user_logged;
	
	@Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.usersearch);
        
        login_user=getIntent();
	    pkg_search=getPackageName();
	    user_logged=login_user.getStringExtra(pkg_search+".user_logged");
        
        Button btnfind = (Button)findViewById(R.id.btnfind);
        btnfind.setOnClickListener(new View.OnClickListener() 
        {
        public void onClick(View v) 
        {   
        
        search = ProgressDialog.show(Search.this, "Searching...", "Wait please...", true,false);
        query_myuser = new ArrayList<String>();
        new Thread(new Runnable() 
		    {
		    public void run()
		    {
				String result = "";
	        	EditText usersearch= (EditText) findViewById(R.id.usersearch); 
	        	String user_search= usersearch.getText().toString();
	        	
	        	//Username da inviare al web service
	        	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	        	nameValuePairs.add(new BasicNameValuePair("user_search",user_search));
	        	nameValuePairs.add(new BasicNameValuePair("username",user_logged));
	        	InputStream is=null;
	        	//Faccio il post http
	        	try
	        	{
	        		HttpClient httpclient = new DefaultHttpClient();
	        	    HttpPost httppost = new HttpPost("http://followdroid.it/script/search_user.php");
	        	    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	        	    HttpResponse response = httpclient.execute(httppost);
	        	    HttpEntity entity = response.getEntity();
	        	    is = entity.getContent();
	        	
	        	    //Converte la risposta HTTP in string
	        		BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
	        	    StringBuilder sb = new StringBuilder();
	        	    String line = null;
	        	    while ((line = reader.readLine()) != null) 
	        	    {
	        	    	sb.append(line + "\n");
	        	    }
	        	    
	        	    is.close();
	        	    result=sb.toString();
	        	}
	        	catch(Exception e)
	        	{
	        		handler.sendEmptyMessage(2);
	        	}
	        	 
	        	//Metto insieme i dati JSON
	        	try
	        	{
	        		JSONArray jArray = new JSONArray(result);
	        	    if(result!=null)
	        	    {
	        	    	for(int i=0;i<jArray.length();i++)
	        	    	{
	        	    		JSONObject json_data = jArray.getJSONObject(i);
	        	    		user_search=json_data.getString("username");
	        	    		query_myuser.add(i,json_data.getString("username"));
	        	    	}
	        	    	handler.sendEmptyMessage(1);
	        	    }
	        	    else
	        	    {
	        	    	handler.sendEmptyMessage(0);
	        	    }
	        	}
	        	catch(JSONException e)
	        	{
	        		handler.sendEmptyMessage(0);
	        	}
		    }
	        	
	        	
		}).start();//Thread		

	}//onclick
        });}
	
	
//Riempie la ListView con i risultati della ricerca
	public void riempilista()
	{
		ListView lv_search = (ListView) findViewById(R.id.lvresult);     
        ArrayList<Person> personList=new ArrayList<Person>();

        Person people;
        for(int i=0;i<query_myuser.size();i++)
        {
        		people=new Person(query_myuser.get(i),"",R.drawable.newsearch);
        		personList.add(people);
        }
       
        ArrayList<HashMap<String, Object>> data=new ArrayList<HashMap<String,Object>>();   
        for(int i=0;i<personList.size();i++){
             Person p=personList.get(i);
             HashMap<String,Object> personMap=new HashMap<String, Object>();
                personMap.put("image", p.getPhotoRes());
                personMap.put("name", p.getName());
                data.add(personMap);
        }
       
        String[] from={"image","name"};
        int[] to={R.id.personImage,R.id.personName};
        
        SimpleAdapter adapter=new SimpleAdapter(
                        getApplicationContext(),
                        data,
                        R.layout.listtview_custom,
                        from,
                        to);
       
        ((ListView)findViewById(R.id.lvresult)).setAdapter(adapter);
        lv_search.setOnItemClickListener(new AdapterView.OnItemClickListener() 
        {
        	public void onItemClick(AdapterView parent, View v,int position, long id)
        	{
        		opzioniutente(position);
        	}
        });
	}
	
	public void opzioniutente(final int a)
	{
		AlertDialog.Builder alert_follow = new AlertDialog.Builder(this);
    	
		alert_follow.setMessage("Do you want to Follow this contact?").setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() 
    	{        
    		//Alla pressione del pulsante "Yes"....
    		public void onClick(DialogInterface dialog, int id) 
    		{
    			follow_user = ProgressDialog.show(Search.this, "Sending request...", "Wait please...", true,false);
    			
    			new Thread(new Runnable() 
    		    {
    				public void run()
    				{
		    			follower=query_myuser.get(a);
		    			if(follower != null)
		    			{
		    				//Username
		    				String result="";
		    	        	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		    	        	nameValuePairs.add(new BasicNameValuePair("myuser",user_logged));
		    	        	nameValuePairs.add(new BasicNameValuePair("follow",follower));
		    	        	InputStream is=null;
		    	        	//Faccio il post http
		    	        	try
		    	        	{
		    	        		HttpClient httpclient = new DefaultHttpClient();
		    	        	    HttpPost httppost = new HttpPost("http://followdroid.it/script/ififollow.php");
		    	        	    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		    	        	    HttpResponse response = httpclient.execute(httppost);
		    	        	    HttpEntity entity = response.getEntity();
		    	        	    is = entity.getContent();
		    	        	
		    	        	    //Converte la risposta HTTP in string
		    	        		BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
		    	        	    StringBuilder sb = new StringBuilder();
		    	        	    String line = null;
		    	        	    while ((line = reader.readLine()) != null) 
		    	        	    {
		    	        	    	sb.append(line + "\n");
		    	        	    }
		    	        	    is.close();
		    	        	    result=sb.toString();
		    	        	}
		    	        	catch(Exception e)
		    	        	{
		    	        		handlerififollow.sendEmptyMessage(0);
		    	        	}
		    	        	 
		    	        	//Metto insieme i dati JSON
		    	        	try
		    	        	{
		    	        	    JSONArray jArray = new JSONArray(result);
		    	        	    if(result!=null)
		    	        	    {
		    	        	    	handlerififollow.sendEmptyMessage(1);
		    	        	    }
		    	        	}
		    	        	catch(JSONException e)
		    	        	{
		    	        		//Username e password da inviare al web service
			    	    		nameValuePairs = new ArrayList<NameValuePair>();
			    	    		nameValuePairs.add(new BasicNameValuePair("myuser",user_logged));
			    	    		nameValuePairs.add(new BasicNameValuePair("follow",follower));
			    	    		is=null;
			    		
			    	    		//Faccio il post http
			            		try
			            		{
			            			HttpClient httpclient = new DefaultHttpClient();
			            			HttpPost httppost = new HttpPost("http://followdroid.it/script/insert_new_follower.php");
			            			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			            			HttpResponse response = httpclient.execute(httppost);
			            	    	HttpEntity entity = response.getEntity();
			            	    	is = entity.getContent();
			            	    	
			            	    	handler_send_req.sendEmptyMessage(1);
			            	    		
			            		}
			            		catch(Exception ex)
			            		{
			            			handler_send_req.sendEmptyMessage(2);
			            		}       	
			    	    	}
			    	    	
		    	        	}
		    				else
			    	    	{
			    	    		handler_send_req.sendEmptyMessage(0);
			    	    	}
		    			}
    		    }).start();
    			
    	    }
    	}).setNegativeButton("No", new DialogInterface.OnClickListener()
    	{
    		//Alla pressione del pulsante "No"....
    		public void onClick(DialogInterface dialog, int id)
    		{
    			dialog.cancel();
    	    }
    	}).show();
	}
	
	public Handler handler_send_req = new Handler() 
    {
    	public void handleMessage(Message msg) {
    		follow_user.dismiss();
    		if (msg.what==0) 
            {
                //Risultati non trovati
            	Toast.makeText(Search.this, "Error! Try again (or later) please...", Toast.LENGTH_LONG).show();
            }
    		if (msg.what==1) 
            {
    			Toast.makeText(Search.this, "You want to follow "+follower, Toast.LENGTH_LONG).show();
            }
            if (msg.what==2)
            {
            	//Errore di conversione
            	Toast.makeText(Search.this, "Error! Try again please...", Toast.LENGTH_LONG).show();
            }
    	}
    };
    
    public Handler handlerififollow = new Handler() 
    {
    	public void handleMessage(Message msg) {
    		follow_user.dismiss();
    		if (msg.what==0) 
            {
    			Toast.makeText(Search.this, "Error! Try again please...", Toast.LENGTH_LONG).show();
            }
    		if (msg.what==1) 
            {
    			Toast.makeText(Search.this, "You have already submitted a request to this contact. Check in 'Friends' or wait for his confirmation.", Toast.LENGTH_LONG).show();
            }
    	}
    };
	
	public Handler handler = new Handler() 
    {
    	public void handleMessage(Message msg) {
    		search.dismiss();
            if (msg.what==1) 
            {
            	Toast.makeText(Search.this, "User found!", Toast.LENGTH_SHORT).show();
            	riempilista();
            }
       
            if (msg.what==0) 
            {
            	Toast.makeText(Search.this, "User not found!", Toast.LENGTH_LONG).show();
            }
            
            if (msg.what==2)
            {
            	//Errore
            	Toast.makeText(Search.this, "Error! Try again please...", Toast.LENGTH_LONG).show();
            }
        }
    };
    
    @Override
    public void onBackPressed() 
	{
    	finish();
    	return;
	}
    
    @Override
    public void onConfigurationChanged(Configuration newConfig) 
	{
        super.onConfigurationChanged(newConfig);
    }
    
}
